const express = require('express')
const multer = require('multer')
const path = require('path')
const database = require('../../database')

const router = express.Router()
const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, './public/avatar')//保存路径
    },
    filename: (req, file, cb) => {
        let extname = path.extname(file.originalname)//获取文件后缀
        let originalname = path.basename(file.originalname, extname)//文件名可别整空格，不然渲染不出来
        cb(null, originalname+Date.now()+extname)//文件名，时间戳不重复处理
    }
})
const upload = multer({ storage: storage })

router.post('/uploadAvatar', upload.single('file'), (request, response) => {
    //console.log(request.file)
    const info = request.auth//之前引入过中间件
    let file = request.file
    let url = 'http://localhost/image/?url='+file.path
    const sql = 'update user set avatar = ? where username = ?'
    database.query(sql, [url, info.username], (error, result) => {
        if(error) {
            response.status(417).end()
        } else {
            response.send({url: url})
        }
    })
})

module.exports = router